/**
 * 医联体配置页面JS
 * User: zhaoming
 * Date: 15-8-17
 * Time: 下午5:58
 * To change this template use File | Settings | File Templates.
 */
$(function(){
    //激活左侧导航菜单
    activeNavBar("MANAGE_OPT_ORG_INFO");
    initSelect2();
    initLayDate("failureDataBegin", "date");
    initLayDate("failureDataEnd", "date");
    initLayDate("effectiveData_I", "date");
    initLayDate("failureData_I", "date");
    initAddForm();
    loadGrid();
    $("#queryBtn").click(function(){
        query();
    });
    $("#resetBtn").click(function(){
        $('#searchForm')[0].reset();
        $('#searchForm').find('.select2-chosen').html('请选择');
    });
    $("#headGoBackBtn").click(function(){
        window.forward(springUrl+ "/web/orgInfo/index");
    });
    $("#addBtn").click(function(){
        openAddDialog();
    });
});

/**
 * 加载数据列表
 */
function loadGrid() {
    var gridTable = jQuery("#gridTable");
    gridTable.jqGrid({
        mtype: "POST",
        url: springUrl + "/web/orgInfo/orgContractPage",
        postData: {
            orgNo: $("#uniqueNo").val()
        },
        datatype: "json",
        autowidth: true,
        height: "100%",
        colModel: [
            {name:'uniqueNo', label:'uniqueNo', index:'', width:50, sortable: false, resizable:false, hidden: true},
            // {name:'orgName',label:'机构名称', index:'',width:100, sortable: false, align:'left'},
            {name:'contractTypeName',label:'合同类型', index:'', width:100, sortable: false, align:'left'},
            {name:'contractAmount',label:'合同金额', index:'', width:100, sortable: false, align:'left'},
            {name:'effectiveData',label:'生效时间', index:'', width:100, sortable: false, align:'left',
                formatter:function(cellValue,options,rowObject){
                    if(cellValue !== null){
                        return moment(cellValue).format("YYYY-MM-DD");
                    }else{
                        return "";
                    }
                }
            },
            {name:'failureData',label:'失效时间', index:'', width:100, sortable: false, align:'left',
                formatter:function(cellValue,options,rowObject){
                    if(cellValue !== null){
                        return moment(cellValue).format("YYYY-MM-DD");
                    }else{
                        return "";
                    }
                }
            },
            {name:'remark',label:'备注', index:'', width:100, sortable: false, align:'left'},
            {name:'', label:'操作', index:'', width:150, fixed:true, sortable:false, resize:false, align:'center',
                formatter:function(cellValue, options, rowObject){
                    var context = "";
                    context += '<button class="mfui-btn mfui-btn-primary mfui-btn-sm" onclick="deleteByUniqueNo(\''+rowObject.uniqueNo+'\')" title="删除">删除</button>';
                    return context;
                }
            }
        ],
        rownumbers: true,//添加左侧行号
        viewrecords: true,
        rowNum: 10,
        rowList: [10, 20, 30],
        sortname: "create_time",
        sortorder: "desc",
        altRows: true,
        pager: "#gridPager",
        jsonReader: { //server返回Json解析设定
            root: "content", //对于json中数据列表
            page: "pageNum",
            total: "total",
            records: "records"
        },
        gridComplete: function (xhr) {
            var ids = $("#gridTable").getDataIDs();
            for(var i=0;i<ids.length;i++){
                var rowData = $("#gridTable").getRowData(ids[i]);
                var day = Math.floor((new Date(rowData.failureData).getTime()- new Date().getTime())/(24*3600*1000));
                if(day < 0){
                    $('#'+ids[i]).find("td").addClass("bg-red");
                }else if(day < 30){
                    $('#'+ids[i]).find("td").addClass("bg-yellow");
                }
            }
        }
    });
    //navButtons
    gridTable.jqGrid('navGrid', "#gridPager",
        {
            add: false,
            addicon: 'fa-plus purple',
            edit: false,
            editicon: 'fa-pencil blue',
            del: false,
            delicon: 'fa-trash red',
            view: false,
            viewicon: 'fa-search-plus orange',
            search: false,
            searchicon: 'fa-search grey',
            refresh: true,
            refreshicon: 'fa-refresh green'
        }
    );
    updatePagerIcons(this);
    resizeJqGrid("gridTable");
}

/**
 * 查询
 */
function query(){
    if($('#searchForm').trigger("validate").isValid()){
        var gridParam = {
            url: springUrl+"/web/orgInfo/orgContractPage",
            postData:{
                orgNo: $("#uniqueNo").val(),
                contractTypeCode : $("#contractTypeCode").val(),
                failureDataBegin : $("#failureDataBegin").val(),
                failureDataEnd : $("#failureDataEnd").val()
            },
            page:1
        };
        $("#gridTable").jqGrid("setGridParam", gridParam).trigger("reloadGrid");
    }
}

/**
 * 根据唯一编号删除
 */
function deleteByUniqueNo(uniqueNo) {
    Alert.confirm("您确定删除该条信息？", function () {
        jQuery.ajax({
            type:"POST",
            dataType:'json',
            url: springUrl+"/web/orgInfo/deleteContract",
            data:{
                uniqueNo:  uniqueNo
            },
            success:function (data) {
                Alert.success("执行成功！", function () {
                    $("#gridTable").trigger("reloadGrid");
                });
            },
            error : function(data){
                Alert.error(data.responseText);
            }
        });
    })
}

/**
 * 初始化
 */
function initAddForm(){
    $("#effectiveData_I").val(moment().format("YYYY-MM-DD"));
    $("#failureData_I").val(moment().add(1, "year").format("YYYY-MM-DD"));
}

/**
 * 打开模态框
 */
function openAddDialog(){
    layer.open({
        id: "add-dialog",
        title: '新增合同',
        zIndex: 5000,
        type: 1,
        skin: 'dialog-blue-class',
        area: ['1000px', '400px'],
        content: $("#add-content"),
        btn: ['保存', '取消'],
        btn1: function(index, layero){
            saveAddForm(index);
        },
        btn2: function(index, layero){
            restAddForm();
        },
        cancel: function(index, layero){
            //右上角关闭回调
            restAddForm();
        }
    });
    //永久显示弹出层纵向滚动条
    $("#add-dialog").css({"overflow-y": "scroll" });
}

/**
 * 保存
 */
function saveAddForm(index){
    if($('#addForm').trigger("validate").isValid()){
        var loading =  layer.msg('正在处理中...', {icon: 16, shade: 0.3, time: 0});
        jQuery.ajax({
            type: "POST",
            dataType: "json",
            url: springUrl + "/web/orgInfo/insertContract",
            data: {
                orgNo : $('#uniqueNo').val(),
                contractTypeCode : $('#contractTypeCode_I').val(),
                contractTypeName : $('#contractTypeCode_I').val()!="" ? $('#contractTypeCode_I option:selected').text() : "",
                contractAmount: $('#contractAmount_I').val(),
                effectiveData : $('#effectiveData_I').val(),
                failureData : $('#failureData_I').val(),
                remark: $('#remark_I').val()
            },
            success: function (data) {
                layer.close(loading);
                Alert.success("数据保存成功!", function(){
                    restAddForm();
                    layer.close(index);
                    $("#gridTable").trigger("reloadGrid");
                });
            },
            error: function(data){
                layer.close(loading)
                Alert.error(data.responseText);
            }
        });
    }
}

/**
 * 重置表单
 */
function restAddForm(){
    $("#add-content").hide();
    $('#addForm')[0].reset();
    $('#addForm').find('.select2-chosen').html('请选择');
    initAddForm();
}